import { useEffect } from "react";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useApplication, useRemoteApplication } from "@share-code/wulian";

import appInfo from "../../publish/app.js";
// import applicationRoles from "../../public/application_business_roles.json";
// import reviewerRoles from "../../public/reviewer_roles.json";
import todoTaskInfo from "../../public/todo_task_roles.json";

export default function applicationModal() {
    const { remoteData, graphqlFetch } = useModel("global");
    const { loadLocalApplication } = useApplication(graphqlFetch);
    const { loadRemoteApplicationInfo, loadRemoteApplicationAuthorization } = useRemoteApplication(remoteData);

    let state = useReactive({
        applicationUuid: window.applicationUuid || appInfo.appUuid,
        applicationName: appInfo.appName,
        applicationInfo: null,
        remoteApplicationInfo: null,
        // reviewerRoles, // 应用审核人角色
        // applicationRoles, //应用内组织角色
        todoTaskInfo, // 待办任务角色
        isExpire: false, // 是否过期
        isStop: false, // 是否暂停授权
        isAuth: false, // 是否功能授权
        startDate: null, // 授权开始日期
        endDate: null, // 授权结束日期
    });

    const loadData = async () => {
        let applicationInfo = await loadLocalApplication(state.applicationUuid);
        setApplicationStateValue({ applicationInfo, applicationName: applicationInfo.aiName || state.applicationName });
    };

    useEffect(() => {
        state.applicationUuid && loadData();
    }, [state.applicationUuid]);

    const loadRemoteApplication = async () => {
        let res = await loadRemoteApplicationInfo(state.applicationUuid);
        if (res) {
            state.remoteApplicationInfo = res;
            let authInfo = await loadRemoteApplicationAuthorization(window.organizationUuid, state.applicationUuid, state.applicationInfo.aiAuty);
            if (authInfo) {
                setApplicationStateValue(authInfo);
                authInfo.isExpire === false && authInfo.isStop === false && (state.isAuth = true);
            }
        }
    };

    useEffect(() => {
        state.applicationUuid && state.applicationInfo?.aiAuty && loadRemoteApplication();
    }, [state.applicationUuid, state.applicationInfo]);

    const setApplicationStateValue = (obj) => {
        for (let key in obj) {
            state[key] = obj[key];
        }
    };

    return {
        ...state,
        setApplicationStateValue,
    };
}
